<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2017/8/16
 * Time: 12:41
 */

header("Content-type: text/html; charset=utf-8");
//define("URL",'http://121.41.84.251:9090');
define("URL",'http://vip.nysochina.com');

class WeinihaigouAction extends Action{
    //获得商品信息
    public function synchroProductInfo($SkuNo,$parenter,$key,$url=URL){
        $content['SkuReqs'] = [$SkuNo];
        $access_token = self::getAccessToken('SkuSynchro',json_encode($content),$key);
        $url = $url.'/api/SkuSynchro.shtml';
        $Header = array();
        $Header[] = "interfacename:SkuSynchro";
        $Header[] = "token:".$access_token;
        $Header[] = "parenter:".$parenter;
        $content = urldecode(json_encode($content));
        $ch = curl_init();
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $Header );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content );
        $result = curl_exec( $ch );
        curl_close( $ch );
        $result = json_decode($result,true);
        if(count($result)>0){
            //调用公众平台
            $proInfo = self::proInfoFormat($result[0]);
            return $proInfo;
        }else{
            Log::write("同步商品失败   ".$SkuNo);
            return false;
        }
    }
    //订单同步
    public function synchroOrder($content,$parenter,$key,$url=URL){
        $content = self::weiniOrderFormat($content);
        $access_token = self::getAccessToken('AddOrderAsync',json_encode($content),$key);
        $url = $url.'/api/AddOrderAsync.shtml';
        $Header = array();
        $Header[] = "interfacename:AddOrderAsync";
        $Header[] = "token:".$access_token;
        $Header[] = "parenter:".$parenter;
        $content = urldecode(json_encode($content));
        $ch = curl_init();
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $Header );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content );
        $result = curl_exec( $ch );
        curl_close( $ch );
        $result = json_decode($result,true);
        if($result&&$result['success']=='true'){
            //调用公众平台
            return true;
        }else{
            Log::write("同步订单失败   ".$result['Message']);
            return false;
        }
    }
    //订单同步结果通知
    public function getOrderResult(){
        $data = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        Log::write("唯妮回调  ".$GLOBALS['HTTP_RAW_POST_DATA']);
        $OrderNo  = $data['OrderNo'];
        $Code     = $data['Code'];
        $Result   = $data['Result'];
        if($Code=='0000'){
            $syncStatus = 1;
        }else{
            $syncStatus = 2;
        }
        $data['syncStatus']=$syncStatus;
        $data['syncOrderSn'] = $Result;
        $data['syncTime'] = date("Y-m-d H:i:s");
        $data["syncMessage"] = $data['Message'];
        R("ApplePie/updateOrder",array($OrderNo,$data));
        echo "{'Success':'true'}";
        return "{'Success':'true'}";
    }

    //库存同步
    public function synchroStock($content,$parenter,$key,$url=URL){
        $access_token = self::getAccessToken('StockSynchro',json_encode($content),$key);
        $url = $url.'/api/StockSynchro.shtml';
        $Header = array();
        $Header[] = "interfacename:StockSynchro ";
        $Header[] = "token:".$access_token;
        $Header[] = "parenter:".$parenter;
        $content = urldecode(json_encode($content));
        $ch = curl_init();
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0);
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $Header );
        curl_setopt ( $ch, CURLOPT_URL, $url);
        curl_setopt ( $ch, CURLOPT_POST, 1);
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content );
        $result = curl_exec( $ch );
        curl_close( $ch );
        $result = json_decode($result,true);
        if(count($result)>0){
            //调用公众平台
            return $result;
        }else{
            Log::write("同步库存失败   ".$result['Message']);
            return false;
        }
    }
    //物流同步
    public function synchroLogistics($content,$parenter,$key,$url=URL){
        $access_token = self::getAccessToken('PostSynchro',json_encode($content),$key);
        $url = $url.'/api/PostSynchro.shtml';
        $Header = array();
        $Header[] = "interfacename:PostSynchro";
        $Header[] = "token:".$access_token;
        $Header[] = "parenter:".$parenter;
        $content = urldecode(json_encode($content));
        $ch = curl_init();
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0);
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $Header );
        curl_setopt ( $ch, CURLOPT_URL, $url);
        curl_setopt ( $ch, CURLOPT_POST, 1);
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $content );
        $result = curl_exec( $ch );
        curl_close( $ch );
        $result = json_decode($result,true);
        if(count($result)>0){
            //调用公众平台
            $data['LogisticName'] = self::getPostCode($result[0]['PostCode']);
            $data['LogisticNo'] = $result[0]['PostNo'];
            $data['IsSend'] = $result[0]['IsSend'];
            return $data;
        }else{
            Log::write("同步物流失败   ".$result['Message']);
            return false;
        }
    }
    //快递公司编码配置
    private function getPostCode($code){
        switch($code){
            case 'shentong':
                return '申通快递';
                break;
            case 'yunda':
                return '韵达快递';
                break;
            case 'yuantong':
                return '圆通速递';
                break;
            case 'zhongtong';
                return '中通速递';
                break;
            case 'ems':
                return 'EMS';
                break;
            case 'shunfeng':
                return '顺丰快递';
                break;
            case 'huitongkuaidi':
                return '百世快递';
                break;
            case 'youzheng':
                return '邮政平邮/小包';
                break;
            case 'debangwuliu':
                return '德邦';
                break;
            case 'guotongkuaidi':
                return '国通快递';
                break;
            case 'kuaiyuntong':
                return '运通快递';
                break;
        }
    }

    //商品格式化
    public function proInfoFormat($data){
        $proInfo['supplierSkuNo'] = $data['SkuNo'];
        $proInfo['serialNumber'] = $data['BarCode'];
        $proInfo['name'] = $data['SkuName'];
        $proInfo['supplyPrice'] = $data['SettlePrice'];
        $proInfo['brand'] = $data['Brand'];
        if(!$data['RetailPrice']){
            $data['RetailPrice']=0;
        }
        $proInfo['fixedPrice'] = $data['RetailPrice'];
        $proInfo['weight'] = $data['Weight']/1000;
        $proInfo['tariff'] = $data['Rate'];
        $proInfo['supportSpecification'] = 0;
        $proInfo['webPageContent'] = $data['Details'];
        $proInfo['country'] = $data['Country'];
        $proInfo['deliveryCode'] = $data['DeliveryCode'];
        $proInfo['categoryId'] = 0;
        $proInfo['createTime'] = date("Y-m-d H:i:s");
        $proInfo['updateTime'] = date("Y-m-d H:i:s");
        $proInfo['proSource']  = 1;
        $proInfo['deleted'] = 0;
        return $proInfo;
    }
    //唯妮订单数据参数整理
    private function weiniOrderFormat($data){
        $temp = null;
        $orderList = null;
        $temp['OrderNo'] = $data['serialNumber'];
        $temp['OrderTime'] = date('YmdHis',strtotime($data['payTime']));
        $temp['ConsigneeNumber'] = $data['phone'];
        $temp['ConsigneeName'] = $data['fullName'];
        $temp['IdCard'] = $data['IDNumber'];
        if($data['province']){
            $addr['province'] = $data['province'];
            $addr['city'] = $data['city'];
            $addr['area'] = $data['country'];
            $addr['street'] = $data['address'];
        }else{
            $addr = R("Product/addressFomate",array($data['address']));
        }
        $addr['province']?$temp['Province'] = $addr['province']:$temp['Province'] = '未知';
        $addr['city']?$temp['City'] = $addr['city']:$temp['City'] = '未知';
        $addr['area']?$temp['District'] = $addr['area']:$temp['District'] = '未知';
        $addr['street']?$temp['DetailedAddres'] = $addr['street']:$temp['DetailedAddres'] = '未知';
        $temp['tax'] ='0';
        $temp['PostalPrice'] = $data['logisticsCost'];
        $data['deliveryCode']?$temp['DeliveryType'] = $data['deliveryCode']:'';
        $price = 0;
        foreach($data['proList'] as $i=>$pro){
            $p = null;
            $p['SkuNo'] = $pro['supplierSkuNo'];
            $p['BuyQuantity'] = $pro['count'];
            $p['Tax'] ='0';
            $pro['customsPrice']&&$pro['customsPrice']>0?$proPrice = $pro['customsPrice']:$proPrice = $pro['price'];
            $p['BuyPrice'] = $proPrice;
            $price+=$proPrice* $pro['count'];
            $orderList[] = $p;
        }
        $temp['GoodsPrice'] = $price;
        $temp['OrderPrice'] = $price+$data['logisticsCost'];
        $temp['OrderItems']=$orderList;
        return $temp;
    }
    //获得 access_token
    private function getAccessToken($interfacename,$content,$key){
        $time = date("Y-m-d");
        return md5($key.$time.$interfacename.$content);
    }


}